﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using PylonC.NETSupportLibrary;
using HalconDotNet;

using URDate;
using URControl;

namespace ImageTest
{
    public partial class Form1 : Form
    {
        private ImageProvider m_imageProvider = new ImageProvider(); /* Create one image provider. */
        //private Bitmap m_bitmap = null; /* The bitmap is used for displaying the image. */

        public Form1()
        {
            InitializeComponent();
        }

        //主程序不应该关心细枝末节，只要知道问谁要到数据，还有要把数据给谁
        URDateHandle URDateCollector = new URDateHandle();
        URControlHandle URController = new URControlHandle();

        //相机全局变量
        HObject ho_Image1 = null;// Local iconic variables 
        HTuple hv_AcqHandle1 = null;// Local control variables 
        HObject ho_Image2 = null;
        HTuple hv_AcqHandle2 = null;

        //声明全局的速度和加速度控制条
        public double SpeedRate;
        public double AccelerationRate;

        int flag = 0;

        Thread tr, tr2;//相机线程
        public bool pause1 = true, pause2 = true;//采集图像标识
        string defaultPath1 = "";//保存路径
        int GainRaw2 = 61;//曝光参数GainRaw 

        void UpdateRobotState(int[] RobotState)
        {
            //只要能取到第一笔数据，就说明连接成功了
            //你也可以检测258寄存器的数据 RobotMode有很多定义，一个口的不同数字表示了多种状态
            if (RobotState[0] == 1)
            {
                string DebugDir = Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory);
                string PicDir = DebugDir + "\\Button\\BtnReady.png";
                this.RobotStatusPic.Image = Image.FromFile(PicDir);
                this.RobotStatusLabel.Text = "已连接";
            }

            if (RobotState[1] == 1)
            {
                string DebugDir = Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory);
                string PicDir = DebugDir + "\\Button\\BtnSecurityStopped.png";
                this.RobotStatusPic.Image = Image.FromFile(PicDir);
                this.RobotStatusLabel.Text = "安全停机";
            }

            if (RobotState[2] == 1)
            {
                string DebugDir = Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory);
                string PicDir = DebugDir + "\\Button\\BtnEmergencyStoped.png";
                this.RobotStatusPic.Image = Image.FromFile(PicDir);
                this.RobotStatusLabel.Text = "紧急停机";
            }

            if (RobotState[3] == 1)
            {
                string DebugDir = Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory);
                string PicDir = DebugDir + "\\Button\\BtnTeaching.png";
                this.RobotStatusPic.Image = Image.FromFile(PicDir);
                this.RobotStatusLabel.Text = "示教模式";
            }

            //最后一个判断UR是不是在运行程序就不做了，很简单，通过258寄存器取值


        }


        //停止： 结束线程
        private void stop1_Click(object sender, EventArgs e)
        {
            HOperatorSet.CloseFramegrabber(hv_AcqHandle1);
            tr.Abort();    
        }
        private void stop2_Click(object sender, EventArgs e)
        {
            HOperatorSet.CloseFramegrabber(hv_AcqHandle2);
            tr2.Abort();
        }

        //保存
        private void save1_Click(object sender, EventArgs e)
        {
            if (pause1 == true)
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                dialog.Description = "请选择一个文件夹";  //打开的文件夹浏览对话框上的描述 
                if (defaultPath1 != "") //首次defaultPath为空，按FolderBrowserDialog默认设置（即桌面）选择  
                {
                    dialog.SelectedPath = defaultPath1;//设置此次默认目录为上一次选中目录 
                }
                if (dialog.ShowDialog() == DialogResult.OK)//按下确定选择的按钮  
                {
                    defaultPath1 = dialog.SelectedPath+ "\\image1";//记录选中的目录  
                }
                defaultPath1 = defaultPath1.Replace ('\\','/');

                pause1 = false;
                save1.Text = "重新拍摄";

            }
            else
            {
                pause1 = true;
                save1.Text = "保存";
            }  
        }
        private void save2_Click(object sender, EventArgs e)
        {
            if (pause2 == true)
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                dialog.Description = "请选择一个文件夹";  //打开的文件夹浏览对话框上的描述 
                if (defaultPath1 != "") //首次defaultPath为空，按FolderBrowserDialog默认设置（即桌面）选择  
                {
                    dialog.SelectedPath = defaultPath1;//设置此次默认目录为上一次选中目录 
                }
                if (dialog.ShowDialog() == DialogResult.OK)//按下确定选择的按钮  
                {
                    defaultPath1 = dialog.SelectedPath + "\\image2";//记录选中的目录  
                }
                defaultPath1 = defaultPath1.Replace('\\', '/');

                pause2 = false;
                save2.Text = "重新拍摄";
            }
            else
            {
                pause2 = true;
                save2.Text = "保存";
            }
        }
        
        //曝光度控件<TrackBar 滑动选择>
        private void GainRawBar2_Scroll_1(object sender, EventArgs e)
        {
            GainRaw2 = GainRawBar2.Value * 10 + 1;
        }


        void GetImage1()
        {
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_Image1);
            HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "gray", -1, "false", "default", "[1]  MV-U500", 0, -1, out hv_AcqHandle1);
            HOperatorSet.GrabImageStart(hv_AcqHandle1, -1);
            while(true)
            {
                while (pause1)
                {
                    ho_Image1.Dispose();
                    HOperatorSet.GrabImageAsync(out ho_Image1, hv_AcqHandle1, -1);
                    HOperatorSet.DispObj(ho_Image1, hWindowControl1.HalconWindow);
                    if (pause1 == false)
                    {
                        HOperatorSet.DispObj(ho_Image1, hWindowControl1_1.HalconWindow);
                        HOperatorSet.WriteImage(ho_Image1, "png", 0, defaultPath1);
                        MessageBox.Show("点击确定\n保存为：image1.png\n路径：" + defaultPath1);//路径提示
                    }
                }
            }
        }
        void GetImage2()
        {
            HOperatorSet.GenEmptyObj(out ho_Image2);
            HOperatorSet.OpenFramegrabber("GigEVision2", 800, 600, 0, 0, 0, 0, "progressive", -1, "default", -1, "false", "default", "00305327999e_Basler_acA380010gc", 0, -1, out hv_AcqHandle2);//打开相机
            HOperatorSet.GrabImageStart(hv_AcqHandle2, -1);
            while (true)
            {
                while (pause2)
                {

                    HOperatorSet.SetFramegrabberParam(hv_AcqHandle2, "GainRaw", GainRaw2);//曝光度参数
                    ho_Image2.Dispose();
                    HOperatorSet.GrabImageAsync(out ho_Image2, hv_AcqHandle2, -1);
                    HOperatorSet.DispObj(ho_Image2, hWindowControl2.HalconWindow);
                    if (pause2 == false)
                    {
                        HOperatorSet.DispObj(ho_Image2, hWindowControl2_1.HalconWindow);
                        HOperatorSet.WriteImage(ho_Image2, "png", 0, defaultPath1);
                        MessageBox.Show("点击确定\n保存为：image2.png\n路径：" + defaultPath1);//路径提示
                    }
                }
            }
        }

        //对于XYZ的线性移动，需要定义一个方法，只需要传入要移动的轴和移动方向(方向就是1和-1)，返回移动的命令
        string GetLinearMovementCommand(string whatAxis, int direction)
        {
            //不管怎么样都要获取当前的坐标值
            double new_X = URDateHandle.Positions_X;
            double new_Y = URDateHandle.Positions_Y;
            double new_Z = URDateHandle.Positions_Z;
            double new_U = URDateHandle.Positions_U;
            double new_V = URDateHandle.Positions_V;
            double new_W = URDateHandle.Positions_W;

            //然后根据点动的按钮，判断要改哪个值(这里不是旋转，只有X,Y,Z三种可能)，直接覆盖到真实的当前XYZ值
            if (whatAxis == "X")
            {
                new_X = ((new_X + 10) * direction);
            }
            else if (whatAxis == "Y")
            {
                new_Y = ((new_Y + 10) * direction);
            }
            else if (whatAxis == "Z")
            {
                new_Z = ((new_Z + 10) * direction);
            }
            else
            {
                //也有可能我不要移动，只是要看指令
            }


            //最后把方向运动的指令发送出去
            string command = "movel(p[" + new_X.ToString() + "," + new_Y.ToString() + "," + new_Z.ToString() + "," + new_U.ToString() + "," + new_V.ToString() + "," + new_W.ToString() + "], a = " + AccelerationRate.ToString() + ", v = " + SpeedRate.ToString() + ")";
            //CustomCommand.Text = command;
            return command;
        }
        //发送停止命令则很简单了，都是发送stopl(1)
        string GetStopCommand()
        {
            string StopCommand = "stopl(1)";
            //CustomCommand.Text = StopCommand;
            return StopCommand;
        }
        //前移键
        private void Forward_MouseDown(object sender, MouseEventArgs e)
        {
            string str = GetLinearMovementCommand("Y", 1);
            URController.Send_command(str);
        }
        private void Forward_MouseUp(object sender, MouseEventArgs e)
        {
            string str = GetStopCommand();
            URController.Send_command(str);
        }
        //后移键
        private void Back_MouseDown(object sender, MouseEventArgs e)
        {
            string str = GetLinearMovementCommand("Y", -1);
            URController.Send_command(str);
        }
        private void Back_MouseUp(object sender, MouseEventArgs e)
        {
            string str = GetStopCommand();
            URController.Send_command(str);
        }
        //左移键
        private void Left_MouseDown(object sender, MouseEventArgs e)
        {
            string str = GetLinearMovementCommand("X", 1);
            URController.Send_command(str);
        }
        private void Left_MouseUp(object sender, MouseEventArgs e)
        {
            string str = GetStopCommand();
            URController.Send_command(str);
        }
        //右移键
        private void Right_MouseDown(object sender, MouseEventArgs e)
        {
            string str = GetLinearMovementCommand("X", -1);
            URController.Send_command(str);
        }
        private void Right_MouseUp(object sender, MouseEventArgs e)
        {
            string str = GetStopCommand();
            URController.Send_command(str);
        }
        //上移键
        private void Up_MouseDown(object sender, MouseEventArgs e)
        {
            string str = GetLinearMovementCommand("Z", 1);
            URController.Send_command(str);
        }
        private void Up_MouseUp(object sender, MouseEventArgs e)
        {
            string str = GetStopCommand();
            URController.Send_command(str);
        }
        //下移键
        private void Down_MouseDown(object sender, MouseEventArgs e)
        {
            string str = GetLinearMovementCommand("Z", -1);
            URController.Send_command(str);
        }
        private void Down_MouseUp(object sender, MouseEventArgs e)
        {
            string str = GetStopCommand();
            URController.Send_command(str);
        }


        /* 在消息框中显示异常。Shows exceptions in a message box. */
        private void ShowException(Exception e, string additionalErrorMessage)
        {
            string more = "\n\n最后错误信息 (可能不属于例外):\n" + additionalErrorMessage;
            MessageBox.Show("异常捕获：\n" + e.Message + (additionalErrorMessage.Length > 0 ? more : ""), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        private void Open_Cam_Click(object sender, EventArgs e)
        {
            try
            {
                /* Open the image provider using the index from the device data. */
                //m_imageProvider.Open(device.Index);
                uint x = 1;
                m_imageProvider.Open(x);
                //OneShot();
                //flag = 5;
            }
            catch (Exception e1)
            {
                ShowException(e1, m_imageProvider.GetLastErrorMessage());
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            tr = new Thread(GetImage1);
            tr.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           // tr = new Thread(GetImage1);
           // tr.Start();

           // tr2 = new Thread(GetImage2);
           // tr2.Start();

        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (tr != null)
            {
                tr.Abort();
            }
            if (tr2 != null)
            {
                tr2.Abort();
            }
        }


    }

}
